/**
 * Created by yoya on 2018/3/28.
 */
var gulp        = require('gulp');
var browserify  = require('browserify');    //转commonjs
var babelify    = require('babelify');  //babel转译器
var glob       = require('glob');   //node包 全局
var source      = require('vinyl-source-stream');   //让代码生成流文件
var buffer      = require('vinyl-buffer');  //让代码转成buffer格式
var uglify      = require('gulp-uglify');   //丑化压缩代码
var sourcemaps  = require('gulp-sourcemaps');   //maps丑化代码映射
var livereload  = require('gulp-livereload');   //监听
var del = require('del');   //这两个库也是用于构建之前先删除的dist输出目录的
var clean = require('gulp-clean');
//样式
var postcss = require('gulp-postcss');  //css转换
var autoprefixer = require('autoprefixer'); //自动补齐属性私有前缀
var cssnext = require('cssnext');   //css新特性
var importCss = require('gulp-import-css');
var cssmin = require('gulp-clean-css');
var rename = require('gulp-rename');
var print = require('gulp-print').default;
var runSequence = require('run-sequence'); //同步执行

// var changed = require('gulp-changed');
//图片压缩
var imagemin = require('gulp-imagemin');      // 图片压缩
var cache = require('gulp-cache');            // 图片缓存，图片替换了才压缩

//gulp
var gulpif = require('gulp-if');
var argv = require('yargs').argv;
var plumber = require('gulp-plumber');

var nodemon = require('gulp-nodemon');

var config = require('./config');

//加载browser-sync模块
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;

gulp.task('watch',function(){
    gulp.watch('./public/css/**.css',['build-scss']);
    gulp.watch('./public/js/**.js',['build-js']);
    gulp.watch('./public/images/**.*{png,jpg,gif,ico}',['minify-img']);
    // gulp.watch('src/img/**/*',['images']);
});

gulp.task('default', function(cb) {
    runSequence(
        'clean', // 第一步：清理目标目录
        'nodemon',
        ['build-js', 'build-scss','minify-img'], // 第二步：打包
        'server',
        'watch', // 第三步：监控
        cb
    );
});

gulp.task('nodemon', function(cb) {
  var started = false;

  return nodemon({
    script: './bin/www'
  }).on('start', function() {
    if (!started) {
      cb();
      started = true;
    }
  });
});

gulp.task('server',function(){
    browserSync.init({
        proxy: 'http://localhost:' + config.port,
        port:config.port
    });
});

gulp.task('clean',function(){
    return gulp.src('./dist',{ read : false})       //src的第二个参数的{read:false}，是不读取文件,加快程序。
        .pipe(clean());
})

// 压缩图片
gulp.task('minify-img', function () {
    return gulp
        .src('./public/images/**/*.{png,jpg,gif,ico}')
        .pipe(cache(imagemin({
            optimizationLevel: 3, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        })))
        .pipe(gulp.dest('./dist/public/images'))
        .pipe(reload({stream:true}));
})

gulp.task('build-js', function () {

    glob('./public/js/**.js', function(err, files) {
        if(err) done(err);
        // console.log(files);

        var tasks = files.map(function(entry) {
            return browserify({ entries: [entry] }) //browerify是将js代码转成标准的commonjs格式的代码
                .transform("babelify", {
                    presets: ["es2015","stage-0"],
                    plugins: ['transform-object-assign']  //转换es6 Object.assign插件
                })  //转换es6代码
                .bundle()   //合并代码
                .on('error', function(err){
                  console.log('---------')
                  console.log(err.loc);
                  console.log(err.codeFrame);
                  console.log(err.message);
                  console.log('---------')
                  this.emit('end');
                })
                .pipe(source(entry))
                .pipe(buffer()) //由于 gulp-uglify 现在不支持 stream，而支持 buffer
                .pipe(sourcemaps.init())    //map代码初始化
                .pipe(gulpif(argv.min, uglify()))   //执行buffer过的压缩代码
                // .pipe(gulpif(argv.min, rename({suffix:'.min'})))
                // .pipe(print())
                .pipe(sourcemaps.write('.maps'))   //生成maps文件
                .pipe(gulp.dest('./dist'))
                .pipe(reload({stream:true}));//livereoload 监听每个文件的变化，让每次构建迭代后都会刷新浏览器
        });
    })
});



gulp.task('build-scss', function(){
    //定义postcss任务流数组
    var processors = [
        autoprefixer({
            browsers:['last 30 version'],
            cascade: false,
            remove: false
        }),
        cssnext()
    ];
    return gulp.src('./public/css/**/*.css')
        .pipe(importCss())  //先执行css模块化
        .pipe(plumber())
        .pipe(postcss(processors))  //后执行post插件
        .pipe(gulpif(argv.min, cssmin()))
        .pipe(gulp.dest('./dist/public/css'))
        .pipe(reload({stream:true}));});
